package com.pengshun.modules.api.system.service.impl;

import com.pengshun.modules.aliyun.OosPush;
import com.pengshun.modules.api.coal.service.dto.UserDto;
import com.pengshun.modules.api.coal.util.SystemPath;
import com.pengshun.modules.api.mapper.SystemMapper;
import com.pengshun.modules.api.coal.repository.VehicleLengthRepository;
import com.pengshun.modules.api.coal.repository.VehicleTypeRepository;
import com.pengshun.modules.api.system.domain.CityDto;
import com.pengshun.modules.api.system.domain.Citys;
import com.pengshun.modules.api.system.form.VehicleForm;
import com.pengshun.modules.api.system.repository.AppVersionRepository;
import com.pengshun.modules.api.system.repository.CityRepository;
import com.pengshun.modules.api.system.service.SystemService;
import com.pengshun.modules.api.system.service.dto.*;
import com.pengshun.modules.api.system.service.mapstruct.AppVersionTodo;
import com.pengshun.modules.common.RedisUtils;
import com.pengshun.modules.aliyun.OosUpload;
import com.pengshun.modules.domain.*;
import com.pengshun.modules.common.BaseResult;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@RequiredArgsConstructor
public class SystemServiceImpl implements SystemService {

    private final SystemMapper systemMapper;

    private final AppVersionRepository appVersionRepository;
    private final AppVersionTodo appVersionTodo;
    private final VehicleTypeRepository vehicleTypeRepository;
    private final VehicleLengthRepository vehicleLengthRepository;
    private final RedisUtils redisUtils;
    private  final MessageSource messageSource;
    @Override
    public BaseResult selectAllProvince() {
        return new BaseResult(0, systemMapper.selectAllProvince());
    }

    @Override
    public BaseResult selectCityBy(Integer provinceId) {
        return new BaseResult(0, systemMapper.selectCityBy(provinceId));
    }

    @Override
    public BaseResult selectDstrictBy(Integer cityId) {

        return new BaseResult(0, systemMapper.selectDstrictBy(cityId));
    }

    @Override
    public BaseResult selectCoalCategory(String name) throws Exception {
        List<Content> colorList = systemMapper.selectBaseCategory(name);
        return new BaseResult(0, colorList);
    }

    @Override
    public BaseResult getVehicleTypeAndLength() {
        List<VehicleLength> vehicleLengths = vehicleLengthRepository.findByStatus(1);
        List<VehicleType> vehicleTypes = vehicleTypeRepository.findByStatus(1);
        VehicleForm vehicleForm = new VehicleForm();
        vehicleForm.setVehicleLengths(vehicleLengths);
        vehicleForm.setVehicleTypes(vehicleTypes);
        return new BaseResult(0, vehicleForm);
    }

    @Override
    public BaseResult upload(MultipartFile files, String path) throws Exception {

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

//        String nameSuffix = format.format(new Date()) + new Random().nextInt(10000);
        //获取上传原图片名称
        String originalFilename = files.getOriginalFilename();
        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        InputStream instream = files.getInputStream();
        Object o = OosUpload.upload(instream, newFileName, path);
        ImageDto dto = new ImageDto(o);
        return new BaseResult(0, dto);
    }

    @Override
    public BaseResult selectimages(Integer type) {
        return new BaseResult(0, systemMapper.selectActivity(type));
    }

    @Override
    public BaseResult appVersion() {
        AppVersion version= systemMapper.selectappVersion();
        return new BaseResult(0,version);
    }

    @Override
    public BaseResult conditions(Integer type) {
        //1煤矿,2经销商,3煤种,4运输公司,
        AllConditions allConditions = new AllConditions();
        //筛选条件
        List<Conditions> screenConditions = new ArrayList<>();
        List<Content> sortcontents = new ArrayList<>();
        List<Content> screencontents = new ArrayList<>();
        if (type == 1) {
            sortcontents.add(new Content(0, "不限", "0"));
            sortcontents.add(new Content(1, "煤炭数排序", "1"));
            sortcontents.add(new Content(2, "营业状态排序", "2"));
            Conditions sortConditions = new Conditions("综合排序", "sort", sortcontents);


            screenConditions.add(new Conditions("煤矿", "type", systemMapper.selectBaseCategory("mine_type")));
            allConditions = new AllConditions(sortConditions, screenConditions);
        }
        if (type == 2) {
            sortcontents.add(new Content(0, "不限", "0"));
            sortcontents.add(new Content(1, "煤炭数排序", "1"));
            sortcontents.add(new Content(2, "营业状态排序", "2"));
            Conditions sortConditions = new Conditions("综合排序", "sort", sortcontents);

            List<Content> contents = systemMapper.selectMineMouth();
            contents.add(0, new Content(0, "不限", "0"));
            screenConditions.add(new Conditions("煤矿", "mineMouthId", contents));

            List<Content> coal = systemMapper.selectBaseCategory("coal_category");;
            coal.add(0, new Content(0, "不限", "0"));
            screenConditions.add(new Conditions("煤种", "categoryCode", coal));


            screencontents.add(new Content(0, "不限", "0"));
            screencontents.add(new Content(1, "营业", "1"));
            screencontents.add(new Content(2, "停业", "2"));
            screenConditions.add(new Conditions("营业状态", "status", screencontents));

            allConditions = new AllConditions(sortConditions, screenConditions);

        }
        if (type == 3) {
            sortcontents.add(new Content(0, "不限", "0"));
            sortcontents.add(new Content(1, "最新发布", "1"));
            sortcontents.add(new Content(2, "价格排序", "2"));
            Conditions sortConditions = new Conditions("综合排序", "sort", sortcontents);

            List<Content> coal =  systemMapper.selectBaseCategory("coal_category");
            coal.add(0, new Content(0, "不限", "0"));
            screenConditions.add(new Conditions("煤种", "categoryCode", coal));
            List<Content> contents = systemMapper.selectMineMouth();
            contents.add(0, new Content(0, "不限", "0"));
            screenConditions.add(new Conditions("煤矿", "mineMouthId", contents));
            screenConditions.add(new Conditions("热值", "calorificValue", systemMapper.selectBaseCategory("coal_calorific")));
            screenConditions.add(new Conditions("全硫分", "allSulphur", systemMapper.selectBaseCategory("all_sulphur")));
            screenConditions.add(new Conditions("灰分", "serchHuifen", systemMapper.selectBaseCategory("serch_huifen")));
            List<Content> contents1 = systemMapper.selectBaseCategory("technology_coal");
            contents1.add(0,new Content(0,"不限","0"));
            screenConditions.add(new Conditions("工艺", "coalTechnologyCode", contents1));

            allConditions = new AllConditions(sortConditions, screenConditions);
        }
        if (type == 4) {
            sortcontents.add(new Content(0, "不限", "0"));
            sortcontents.add(new Content(1, "距离最近", "1"));
            sortcontents.add(new Content(2, "运价最高", "2"));
            sortcontents.add(new Content(3, "信息费最低", "3"));
            sortcontents.add(new Content(4, "最新发布", "4"));
            sortcontents.add(new Content(5, "货运数量", "5"));
            Conditions sortConditions = new Conditions("综合排序", "sort", sortcontents);

            screencontents.add(new Content(0, "全部信息", "0"));
            screencontents.add(new Content(1, "免费信息", "1"));
            screencontents.add(new Content(2, "收费信息", "2"));
            screenConditions.add(new Conditions("信息类型", "infoType", screencontents));

            List<Content> huoyunleixing = systemMapper.selectBaseCategory("transport_type");
            huoyunleixing.add(0, new Content(0, "不限", "0"));
            screenConditions.add(new Conditions("货运类型", "freightTypeCode", huoyunleixing));

            List<Content> huowuType = systemMapper.selectBaseCategory("cargo_type");
            huowuType.add(0, new Content(0, "不限", "0"));
            screenConditions.add(new Conditions("货物类型", "freightTransportCode", huowuType));


            List<Content> vehicleType = systemMapper.selectBaseCategory("car_type");
            vehicleType.add(0, new Content(0, "不限", "0"));
            screenConditions.add(new Conditions("车辆类型", "vehicleTypeId", vehicleType));

            List<Content> vehicleLength = systemMapper.selectBaseCategory("car_length");
            vehicleLength.add(0, new Content(0, "不限", "0"));
            screenConditions.add(new Conditions("车辆长度", "vehicleLengthId", vehicleLength));

            allConditions = new AllConditions(sortConditions, screenConditions);


        }

        if (type == 5) {
            sortcontents.add(new Content(0, "不限", "0"));
            sortcontents.add(new Content(1, "车辆数排序", "1"));
            sortcontents.add(new Content(2, "营业状态排序", "2"));
            Conditions sortConditions = new Conditions("综合排序", "sort", sortcontents);

            screencontents.add(new Content(0, "不限", "0"));
            screencontents.add(new Content(1, "营业", "1"));
            screencontents.add(new Content(2, "停业", "2"));
            screenConditions.add(new Conditions("营业状态", "status", screencontents));

            allConditions = new AllConditions(sortConditions, screenConditions);

        }

        return new BaseResult(0, allConditions);
    }

    @Override
    public BaseResult updateVersion(AppVersionDto version) {
        Object pass = redisUtils.get(SystemPath.APP_VERSION_PATH);
        if (pass == null) {
            return new BaseResult(1,  messageSource.getMessage("SystemServiceImpl.updateVersion.pass", null, Locale.CHINA));
        }
        if (!version.getPass().equals(pass.toString())) {
            return new BaseResult(1,  messageSource.getMessage("SystemServiceImpl.updateVersion.version", null, Locale.CHINA));
        }
        redisUtils.del(SystemPath.APP_VERSION_PATH);
        return new BaseResult(0, appVersionRepository.save(appVersionTodo.toEntity(version)));
    }

    @Override
    public BaseResult selectAllCityBy(CityDto para) {
        List<CityDto> list= systemMapper.findAllCityOrderByFirstLetterSecondLetter();
        List<CityDto> newList=new ArrayList<>();
        String sgin="";
        int i=0;
        for (CityDto city : list) {
            if(!city.getFirstLetter().equals(sgin)){
                newList.add(new CityDto(i,city.getFirstLetter(),i,city.getFirstLetter()));
                sgin=city.getFirstLetter();
                i++;
            }
//            newList.add(new CityDto(city.getCityId(),city.getCity(),city.getProvinceId(),city.getFirstLetter()));
            i++;
        }
        return new BaseResult(0,newList);
    }

    @Override
    public BaseResult selectByCity(CityDto para) {
        List<CityDto> list= systemMapper.selectByCity(para.getCity());
        return new BaseResult(0,list);
    }

    @Override
    public BaseResult contactOurs() {
        PsContactOurs contactOurs=systemMapper.findContactOurs();
        return new BaseResult(0,contactOurs);
    }

    @Override
    public BaseResult suggest(PsSuggest suggest) {
        systemMapper.saveSuggest(suggest.getContent(),suggest.getPhotos() ,suggest.getUserId(),new Date());
        return new BaseResult(0,messageSource.getMessage("submit.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult introduction() {
        PsSuggest contactOurs=systemMapper.findIntroduction();
        return new BaseResult(0,contactOurs);
    }

    @Override
    public BaseResult selectNotice() {
        SystemNotice notice=systemMapper.selectNotice();
        return new BaseResult(0,notice);
    }

    @Override
    public BaseResult selectCustomerList() {
        List<UserDto> list=systemMapper.selectCustomerList();
        return new BaseResult(0,list);
    }

    @Override
    public BaseResult selectMerchantList() {
        List<UserDto> list=systemMapper.selectMerchantList();
        List<UserDto> list1=systemMapper.selectAllCustomerList();
        list.addAll(list1);
        return new BaseResult(0,list);
    }

    public String uploads(MultipartFile file, String path, String fileName) throws Exception {
        String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
        File dest = new File(realPath);
        // 判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        // 保存文件
        file.transferTo(dest);
        return dest.getName();
    }

}
